import 'dart:async';
import 'dart:typed_data';
import 'package:example/datebase/text_data_dto.dart';
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';

class HorizontalLedScreen extends StatefulWidget {
  int mode;
  int dynamicMode;
  List<TextDataDTO> textList;
  Color textColor;
  Color externalColor;
  bool isSelectedTextColor;
  bool? isInvert;
  HorizontalLedScreen({Key? key,
    required this.textList,
    required this.externalColor,
    required this.mode,
    required this.dynamicMode,
    required this.textColor,
    required this.isSelectedTextColor,
    this.isInvert,
  }) : super(key: key);

  @override
  State<HorizontalLedScreen> createState() => _HorizontalLedScreenState();
}

class _HorizontalLedScreenState extends State<HorizontalLedScreen> {
  List<TextDataDTO> textList = [];
  List< List<List<int>> > bitmapMatrixList = [];
  List< List<int> > gridViewList = List.generate(58, (index) => List.generate(20, (index) => 0));
  Timer? timer;
  Timer? timer2;
  bool isInvert = false;
  int smallIndex = 0;
  int bigIndex = 0;
  int currentIndex=0;
  @override
  void initState() {
    // TODO: implement initState
    textList = widget.textList.map((e) => e.copyWith()).toList();
    if(widget.isInvert!=null) isInvert = widget.isInvert!;
    bitmapMatrix();
    switch (widget.dynamicMode){
      case 0:
        certainlyAnimation();
        break;
      case 1:
        displacementAnimation();
        break;
      case 2:
        displacementAnimation();
        break;
      case 3:
          certainlyAnimation();
          flashAnimation();
        break;
    }
    super.initState();
  }

  ///位移动画
  displacementAnimation(){
    timer?.cancel();
    timer = Timer.periodic(const Duration(milliseconds: 50), (timer) {
      setState((){
        if(bitmapMatrixList.isNotEmpty){
          if(widget.dynamicMode==1){
            gridViewList.insert(gridViewList.length-1, bitmapMatrixList[bigIndex][smallIndex]);
            gridViewList.removeAt(0);
            smallIndex++;
            if(smallIndex>bitmapMatrixList[bigIndex].length-1){
              smallIndex = 0;
              bigIndex++;
            }
            if(bigIndex>bitmapMatrixList.length-1){
              bigIndex = 0;
            }
          }else if(widget.dynamicMode==2){
            gridViewList.insert(0, bitmapMatrixList[bitmapMatrixList.length-1-bigIndex][bitmapMatrixList[bitmapMatrixList.length-1-bigIndex].length-1-smallIndex]);
            gridViewList.removeAt(gridViewList.length-1);
            smallIndex++;
            if(smallIndex>bitmapMatrixList[bitmapMatrixList.length-1-bigIndex].length-1){
              smallIndex = 0;
              bigIndex++;
            }
            if(bigIndex>bitmapMatrixList.length-1){
              bigIndex = 0;
            }
          }
        }
      });
    });
  }

  ///固定
  certainlyAnimation(){
     bigIndex = 0;
     smallIndex=0;
    gridViewList.forEachIndexed((index,element) {
      if(bitmapMatrixList.isNotEmpty){
        gridViewList[index] = bitmapMatrixList[bigIndex][smallIndex];
        smallIndex++;
        if(smallIndex>bitmapMatrixList[bigIndex].length-1){
          smallIndex = 0;
          bigIndex++;
        }
        if(bigIndex>bitmapMatrixList.length-1){
          bigIndex = 0;
        }
      }
    });
  }

  ///闪烁
  flashAnimation(){
    timer2?.cancel();
    timer2 = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      setState((){
        currentIndex++;
        if(currentIndex>1){
          currentIndex = 0;
        }
      });
    });
  }

  @override
  void didUpdateWidget(covariant HorizontalLedScreen oldWidget) {
    // TODO: implement didUpdateWidget
    print("${widget.textList} ${oldWidget.textList} ");
    if(widget.textList != textList){
      print("didUpdateWidget:  ");
      setState((){
        textList = widget.textList.map((e) => e.copyWith()).toList();
        bitmapMatrix();
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  ///判断是否翻转，使用对应得生成方法
  bitmapMatrix(){
    dateReset();
    if(!isInvert){
      bitmapMatrix1();
    }else{
      bitmapMatrix2();
    }
    if(widget.dynamicMode==0||widget.dynamicMode==3){
      certainlyAnimation();
    }
  }

  ///数据复原
  dateReset(){
    setState((){
      gridViewList = List.generate(58, (index) => List.generate(20, (index) => 0));
      smallIndex = 0;
      bigIndex = 0;
      bitmapMatrixList = [];
    });
  }

  ///生成便于赋值的位图矩阵
  bitmapMatrix1(){
    List<TextDataDTO> textList= widget.textList;
    bitmapMatrixList = [];
    textList.forEachIndexed((index,element) {
      List<List<int>> bitmapMatrix = [];
      bitmapMatrix = setTextData(element.data!);
      bitmapMatrix = setStraightenTextData(bitmapMatrix);
      bitmapMatrix = setFillInData2(bitmapMatrix);

      ///处理文字颜色index
      bitmapMatrix.forEachIndexed((index1, element1) {
        element1.forEachIndexed((index2, element2) {
          if(element2==1){
            bitmapMatrix[index1][index2] = index+1;
          }
        });
        // print("处理文字颜色index$element1");
      });
      bitmapMatrixList.add(bitmapMatrix);
    });

    if(widget.dynamicMode==1){
      bitmapMatrixList.add(List.generate(58, (index) => List.generate(20, (index) => 0)));
    }else if(widget.dynamicMode==2){
      bitmapMatrixList.insert(0,List.generate(58, (index) => List.generate(20, (index) => 0)));
    }else{
      bitmapMatrixList.add(List.generate(58, (index) => List.generate(20, (index) => 0)));
    }
  }

  ///生成便于赋值的位图矩阵
  bitmapMatrix2(){
    List<TextDataDTO> textList= widget.textList;
    bitmapMatrixList = [];
    textList.forEachIndexed((index,element) {
      List<List<int>> bitmapMatrix = [];
      bitmapMatrix = setTextData(element.data!);

      bitmapMatrix = setStraightenTextData(bitmapMatrix);

      // print("bitmapMatrix ${bitmapMatrix.length}");
      // bitmapMatrix.forEach((element) {
      //   print(" ${element.map((e) => e).toList()}");
      // });
      bitmapMatrix = setFillInData(bitmapMatrix);
      // print("bitmapMatrix:补充 ${bitmapMatrix.length}");
      // bitmapMatrix.forEach((element) {
      //   print(" ${element.map((e) => e).toList()}");
      // });
      ///处理文字颜色index
      bitmapMatrix.forEachIndexed((index1, element1) {
        element1.forEachIndexed((index2, element2) {
          if(element2==1){
            bitmapMatrix[index1][index2] = index+1;
          }
        });
      });
      bitmapMatrix = setFlipData(bitmapMatrix);
      bitmapMatrix = setFlipData2(bitmapMatrix);
      bitmapMatrixList.add(bitmapMatrix);
    });
    if(widget.dynamicMode==1){
      bitmapMatrixList.add(List.generate(58, (index) => List.generate(20, (index) => 0)));
    }else if(widget.dynamicMode==2){
      bitmapMatrixList.insert(0,List.generate(58, (index) => List.generate(20, (index) => 0)));
    }else{
      bitmapMatrixList.add(List.generate(58, (index) => List.generate(20, (index) => 0)));
    }
  }



  @override
  void dispose() {
    // TODO: implement dispose
    timer?.cancel();
    timer2?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
        builder: (context,cons) {
          double width;
          double height;
          if(cons.maxWidth*20/58<cons.maxHeight){
            width = cons.maxWidth;
            height = cons.maxWidth*20/58;
          }
          else{
            width = cons.maxHeight*58/20;
            height = cons.maxHeight;
          }
          return Stack(
            alignment: Alignment.center,
            children: [
              Container(
                width: width,
                height: height,
                decoration: getBoxDecoration(),
                child: Row(
                  children: gridViewList.map((e1) => Column(
                    children: e1.map((e2) => Container(
                      width: width/58,
                      height: height/20,
                      decoration:  BoxDecoration(
                          color: e2!=0
                              ?widget.isSelectedTextColor?widget.textColor:Color(textList[e2-1].color!)
                              :widget.externalColor,
                          border: Border.all(
                              width: 1,
                              color: Colors.black
                          )
                      ),
                      // child: Text("$index",style: const TextStyle(fontSize: 5),),
                    )).toList(),
                  )).toList(),
                ),
              ),
              AnimatedContainer(
                width: width,
                height: height,
                duration: const Duration(milliseconds: 1000,),
                color: currentIndex==0?Colors.transparent:Colors.black54,
                // child: Text("${currentIndex}",style: TextStyle(fontSize: 20,color: Colors.white),),
              ),Positioned(
                top: 5,
                right: 5,
                child: InkWell(
                    onTap: (){
                      setState((){
                        isInvert = !isInvert;
                        bitmapMatrix();
                      });
                    },
                    child: Icon(Icons.flip_camera_android,color: isInvert?Colors.blue:Colors.white,size: 20,)),
              ),

            ],
          );
        }
    );
  }
  ///装饰设置
  Decoration getBoxDecoration(){
    return BoxDecoration(
      borderRadius: BorderRadius.circular(4),
      gradient:widget.mode==0?const LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: [
          Color(0xFFFF0000),
          Color(0xFFFFFF00),
          Color(0xFF00FF00),
          Color(0xFF00FFFF),
          Color(0xFF0000FF),
          Color(0xFFFF00FF),
          Color(0xFFFF0000),
        ],
      )
          : widget.mode == 1? const RadialGradient(
        colors: [
          Color(0xFFFF0000),
          Color(0xFFFFFF00),
          Color(0xFF00FF00),
          Color(0xFF00FFFF),
          Color(0xFF0000FF),
          Color(0xFFFF00FF),
          Color(0xFFFF0000),
        ],
      )
          : const SweepGradient(
        startAngle: 0,
        endAngle: 3.1415926 * 2,
        colors: [
          Color(0xFFFF0000),
          Color(0xFFFFFF00),
          Color(0xFF00FF00),
          Color(0xFF00FFFF),
          Color(0xFF0000FF),
          Color(0xFFFF00FF),
          Color(0xFFFF0000),
        ],
      ),
    );
  }

  ///Uint8List转换为list<int>
  List<List<int>> setTextData(Uint8List bArr,) {
    print("setTextData::::0   ${bArr}");
    int? heightCount = 12;
    int? widthCount = bArr.length ~/ 2;
    int length = bArr.length ~/ 2;

    List<int> iArr = List.generate(length, (index) => 0);
    for (int i = 0; i < bArr.length / 2; i++) {
      int i2 = i * 2;
      int i3 = bArr[i2] & -1;
      int i4 = bArr[i2 + 1] & -1;
      int i5 = heightCount;
      iArr[i] = (i4 >> (16 - i5)) | (i3 << (i5 - 8));
    }

    List<List<int>> list1 = [];
    for (int i6 = 0; i6 < widthCount; i6++) {
      List<int> list0 = [];
      for (int i7 = 0; i7 < heightCount; i7++) {
        int i8 = (iArr[i6] >> i7) & 1;
        list0.add(i8);
      }
      list1.add(list0);
    }
    return list1;
  }

  ///摆正文字方法
  List<List<int>> setStraightenTextData(List<List<int>> bitmapMatrix){
    List<List<int>> straightenTextData=[];
    bitmapMatrix.forEachIndexed((index,element) {
      straightenTextData.add(element.mapIndexed((index,e) => element[element.length-1-index]).toList());
    });
    return straightenTextData;
  }

  ///左右补位方法
  List<List<int>> setFillInData(List<List<int>> bitmapMatrix){
    List<List<int>> fillInData=[];
    int length = 20-bitmapMatrix.length;
    int leftHalf = length~/2;
    int rightHalf = length-leftHalf;
    for(int i=0;i<leftHalf;i++){
      fillInData.add(List.generate(12, (index) => 0));
    }
    fillInData.addAll(bitmapMatrix);
    for(int i=0;i<rightHalf;i++){
      fillInData.add(List.generate(12, (index) => 0));
    }

    return fillInData;
  }

  ///位图翻转方法
  List<List<int>> setFlipData(List<List<int>> bitmapMatrix){
    List<List<int>> flipData=List.generate(12, (index) => []);
    for(int i=0;i<flipData.length;i++){
      bitmapMatrix.forEachIndexed((index, element) {
        flipData[i].add(element[i]);
      });
    }
    return flipData;
  }

  ///位图翻转方法2
  List<List<int>> setFlipData2(List<List<int>> bitmapMatrix){
    List<List<int>> flipData=[];
    for(int i=0;i<bitmapMatrix.length;i++){
      List<int> list = [];
      bitmapMatrix[i].forEachIndexed((index,element) {
        list.add(bitmapMatrix[i][bitmapMatrix[i].length-1-index]);
      });
      flipData.add(list);
    }
    return flipData;
  }

  ///上下补位方法
  List<List<int>> setFillInData2(List<List<int>> bitmapMatrix){
    List<List<int>> fillInData=[];
    bitmapMatrix.forEachIndexed((index,element) {
      List<int> list = [];
      list.add(0);
      list.add(0);
      list.add(0);
      list.add(0);
      list.addAll(element);
      list.add(0);
      list.add(0);
      list.add(0);
      list.add(0);

      fillInData.add(list);
    });
    return fillInData;
  }

}
